﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GPMS.Model;

namespace GPMS.Web.Controllers
{
    using GPMS.BLL;
    using System.IO;
    using System.Data;
    /// <summary>
    /// 后台管理控制器
    /// </summary>
    public class AdministratorController : BaseController
    {

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Setting()
        {
            ViewData["roles"] = gpmsDb.Roles.Where(r => !r.IsDeleted && r.IsMain).ToList();
            return View(SettingHelper.Get(gpmsDb));
        }

        [HttpPost]
        public ActionResult Setting(Setting setting, FormCollection collection)
        {
           
           try
           {
               Setting model = SettingHelper.Get(gpmsDb);
               UpdateModel(model, collection);
               gpmsDb.SaveChanges();
               return Success(null);
           }
           catch (Exception ex)
           {
               return JsonError("更新失败:" + ex.Message);
           }
        }

        public ActionResult Import()
        {
            Guid userid=AccountHelper.GetLoginUserID(Request);
            ImportUser model = new ImportUser();
            model.FileList = FileHelper.GetUserFileList(userid, gpmsDb)
                .Where(f => f.Name.EndsWith("xls", StringComparison.CurrentCultureIgnoreCase)).ToList();
            model.RoleList = AccountHelper.GetUserRole(gpmsDb);
            model.SpecialtyList = gpmsDb.Specialties.ToList();
            return View(model);
        }

        [HttpPost]
        public ActionResult Import(ImportUser model,FormCollection collection)
        {
            try
            {
                List<UserRoleVM> permission = AccountHelper.GetUserRole(gpmsDb);
                foreach (var item in collection.AllKeys)
                {
                    Guid roleid;
                    if (Guid.TryParse(item,out roleid))
                    {
                        permission.SingleOrDefault(p => p.Role.RoleID == roleid)
                       .Permission = (bool)collection.GetValue(item).ConvertTo(typeof(bool));
                    }
                   
                }


                GPMS.Model.File file = FileHelper.Get(model.FileID, gpmsDb);
                DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/upload"));
                if (!dir.Exists)
                {
                    dir.Create();
                }
                DataTable dt = ExcelToSQL.ExcelToDataTable(Path.Combine(Server.MapPath("~/upload"), file.FileID.ToString()));
                int count = 0;
                foreach (var item in dt.Rows)
                {
                    DataRow dr = item as DataRow;
                    UserInfo user = new UserInfo()
                    {
                        UserID = Guid.NewGuid(),
                        UserName = dr[0].ToString(),
                        RealName = dr[1].ToString(),
                        Sex = dr[2].ToString() == "男",
                        Email = dr[3].ToString(),
                        Password = dr[4].ToString(),
                        Phone = dr[5].ToString(),
                        SpecialtyID = model.SpecialtyID,
                        CreateDate=DateTime.Now,
                        UserIdentity = dr[0].ToString()
                    };
                    if (!gpmsDb.UserInfos.Any(u => u.UserName == user.UserName))
                    {
                        gpmsDb.UserInfos.AddObject(user);
                        gpmsDb.SaveChanges();
                        user = AccountHelper.Get(user.UserID, gpmsDb);
                        permission.ForEach(p =>
                        {
                            if (p.Permission)
                            {
                                user.Roles.Add(p.Role);
                            }
                        });
                        gpmsDb.SaveChanges();
                        count++;
                    }
                }
                return Success("成功导入" + count.ToString() + "个用户！");
            }
            catch (Exception ex)
            {

                return JsonError("导入失败：" + ex.Message);
            }
            
        }

    }
}
